package com.xiaoming.backend.service.impl;

import com.xiaoming.backend.dao.impl.UserDao;
import com.xiaoming.backend.dto.request.LoginRequest;
import com.xiaoming.backend.dto.request.RegisterRequest;
import com.xiaoming.backend.dto.response.Token;
import com.xiaoming.backend.dto.response.UserResponse;
import com.xiaoming.backend.entity.db.po.UserPO;
import com.xiaoming.backend.entity.orm.User;
import com.xiaoming.backend.result.exception.AppErrorException;
import com.xiaoming.backend.result.exception.error.AppError;
import com.xiaoming.backend.service.IAuthService;
import com.xiaoming.backend.util.JwtUtil;
import com.xiaoming.backend.util.EntityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements IAuthService {
    private final UserDao userDao;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;
    @Override
    @Transactional
    public UserResponse register(RegisterRequest request) {
        List<UserPO> userPOS = userDao.getUserInfoForUserName(request.getUserName());
        if (!userPOS.isEmpty()) {
            throw new AppErrorException(AppError.USER_ERROR);
        }
        request.setPassWard(passwordEncoder.encode(request.getPassWard()));

        User user = userDao.insertUserForUserInfo(request);
        return EntityUtil.userTOUserResponse(user);
    }
    @Override
    public Token login(LoginRequest request) {
        List<UserPO> userPOS = userDao.getUserInfoForUserName(request.getUsername());
        if (userPOS == null || userPOS.isEmpty() || !passwordEncoder.matches(request.getPassword(), userPOS.get(0).getPassWard())) {
            throw new AppErrorException(AppError.LOGIN_ERROR);
        }
        User user = EntityUtil.userPOTOUser(userPOS.get(0));
        String token = jwtUtil.generateToken(user.getUserName(), user.getFacilityId());
        return Token.builder().token(token).build();
    }
}